﻿#include "filetool.h"

#include <QFile>
#include <QCryptographicHash>

namespace Common {

	QSettings * FileTool::g_iniSettings = NULL;


	FileTool::FileTool(QObject *parent)
		: QObject(parent)
	{

	}

	FileTool::~FileTool()
	{

	}

	bool FileTool::writeDataFile(QString filePath, QByteArray buff)
	{
		if (filePath.isEmpty())
		{
			return false;
		}

		QFile file(filePath);
		if (!file.open(QIODevice::ReadWrite | QIODevice::Append))
		{
			return false;
		}
		// 写操作
		QDataStream dataStream(&file);
		dataStream << buff;
		file.close();
		return true;
	}

	bool FileTool::readDataFile(QString filePath, QByteArray & buff)
	{
		if (filePath.isEmpty())
		{
			return false;
		}

		QFile file(filePath);
		if (!file.open(QIODevice::ReadWrite | QIODevice::Append))
		{
			return false;
		}

		buff = file.readAll();
		file.close();
		return true;
	}

	void FileTool::setInilSettings(QSettings * settings)
	{
		if (g_iniSettings)
		{
			delete g_iniSettings;
		}
		g_iniSettings = settings;
	}

	QSettings * FileTool::getIniSettings()
	{
		return g_iniSettings;
	}

	void FileTool::setIniValue(const QString & group, const QString & key, const QVariant & value, const bool isForce)
	{
		if (g_iniSettings == nullptr)
		{
			return;
		}

		if (isForce || !g_iniSettings->contains(key))
		{
			QString fullName = QString("%1/%2").arg(group).arg(key);
			g_iniSettings->setValue(fullName, value);
		}
	}

	QVariant FileTool::getIniValue(const QString & group, const QString & key, const QVariant & value)
	{
		if (g_iniSettings == nullptr)
		{
			return QVariant();
		}

		g_iniSettings->beginGroup(group);
		if (!g_iniSettings->contains(key))
		{
			g_iniSettings->setValue(key, value);
		}

		QVariant val = g_iniSettings->value(key, value);
		g_iniSettings->endGroup();
		return val;
	}

	QString FileTool::MD5(QString text)
	{
		QByteArray bb;
		bb = QCryptographicHash::hash(text.toLocal8Bit(), QCryptographicHash::Md5);
		return QString().append(bb.toHex());
	}

	QString FileTool::MD5File(QString fileName)
	{
		QFile theFile(fileName);
		theFile.open(QIODevice::ReadOnly);
		QByteArray ba = QCryptographicHash::hash(theFile.readAll(), QCryptographicHash::Md5).toHex();
		theFile.close();
		return QString(ba);
	}

} // namespace Common
